package com.ajavaer.framework.common.tools;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.file.attribute.FileTime;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class ZipTools {

    public static void write(ZipOutputStream zos, File[] readyToZip)
            throws IOException {
        for (File toZip : readyToZip) {
            addFile(zos, toZip, "");
        }
    }

    private static void addFile(ZipOutputStream out, File f, String base) throws IOException {
        if (f.isDirectory()) {
            File[] fl = f.listFiles();
            ZipEntry entry = new ZipEntry(base + "/");
            FileTime time = FileTime.fromMillis(f.lastModified());
            entry.setLastModifiedTime(time);
            out.putNextEntry(entry);
            base = base.length() == 0 ? "" : base + "/";
            for (int i = 0; i < fl.length; i++) {
                if (fl[i].isFile()) {
                    addFile(out, fl[i], base);
                } else {
                    addFile(out, fl[i], base + fl[i].getName());
                }
            }
        } else if (f.isFile()) {
            byte[] buf = new byte[8192];
            int len;
            ZipEntry entry = new ZipEntry(base + f.getName());
            FileTime time = FileTime.fromMillis(f.lastModified());
            entry.setLastModifiedTime(time);
            out.putNextEntry(entry);
            try(BufferedInputStream in = new BufferedInputStream(
                    new FileInputStream(f))){
                while ((len = in.read(buf)) > 0) {
                    out.write(buf, 0, len);
                }
            }
        }
    }

}
